<template>
    <div>
        <edu-dialog
            title="个人信息激活"
            width="90%"
            ref="ActiveDialog"
            :close-on-press-escape="closeOnPressEscape"
            :show-close="showClose"
        >
        <span class="titleMsg">说明：“激活功能”主要用于重要信息确认，请务必准确填写。如后续有修改，请联系教务老师。</span>
            <div>
                <el-tabs v-model="activeName" type="border-card">
                    <el-tab-pane :label="dynamic.name" :name="dynamic.id" v-for="(dynamic, index) in dynamicValidateForms" :key="index">
                        <el-form id='IE-target-form' label-position="left" ref="activationForm" :model="dynamic">
                            <el-row :gutter="20">
                                <el-col
                                    :span="12"
                                    v-for="(row,index) in dynamic.stuActivationFieldConfigs"
                                    :key="index"
                                >
                                    <el-form-item
                                        :label="setLabel(row)"
                                        :prop="'stuActivationFieldConfigs.'+index+'.columnValue'"
                                        :rules="getRules(row)"
                                    >
                                    <!-- 设置label的提示信息 -->
                                    <span v-for='(item,index) in tabMsg' :key='index'>
                                        <span class="setSize" v-if="item.label == row.nameZH">{{item.value}}</span>
                                    </span>
                                    <!-- 导师1、导师2开始 -->
                                        <template v-if="row.fieldId == 77 || row.fieldId === 78">
                                        <select-For-Page
                                            URL="/api/studentservice/userInfo/studentOrTeacherPageList"
                                            v-model="row.columnValue"
                                            :queryType="1"
                                            :val="row.columnValue"
                                            :valId="row.fieldId"
                                            :ifDisabled="row.isUpdate == 0? true : false"
                                            @return-value-to-label="getValueToLabel">
                                        </select-For-Page>
                                        </template>
                                        <!-- 导师1、导师2结束 -->
                                        <template v-else-if="row.type=='input'">
                                        <el-input
                                            style="width:100%"
                                            :disabled="!row.isUpdate"
                                            v-model="row.columnValue"
                                            :maxlength="row.length"
                                        ></el-input>
                                        </template>
                                        <!-- 火车终点站  开始-->
                                        <template v-if="row.fieldId == 25 && endStation.length > 0">
                                        <pager-select
                                            :data="endStation"
                                            :notClear="true"
                                            v-model="row.columnValue">
                                        </pager-select>
                                        </template>
                                        <!-- 火车终点站  结束-->
                                        <!-- 对方合作院校  开始 -->
                                        <template v-else-if="row.fieldId == '166'">
                                        <el-select
                                            v-model="row.columnValue"
                                            style="width:100%"
                                            clearable
                                        >
                                            <el-option
                                                v-for="item in universList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                        </template>
                                        <!-- 对方合作院校  结束 -->
                                        <!-- 培养专业、招生专业  开始-->
                                        <template v-else-if="row.fieldId == '69'">
                                        <el-select
                                            v-model="row.columnValue"
                                            style="width:100%"
                                            clearable
                                        >
                                            <el-option
                                                v-for="item in majorList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                        </template>
                                        <template v-else-if="row.fieldId == '67'">
                                        <el-input
                                            style="width:100%"
                                            disabled
                                            v-model="row.columnValue"
                                        ></el-input>
                                        </template>
                                        <!-- 培养专业、招生专业  结束 -->
                                        <!-- 学籍专业  开始 -->
                                        <template v-else-if="row.fieldId == '68'">
                                        <el-select
                                            v-model="row.columnValue"
                                            style="width:100%"
                                            clearable
                                        >
                                            <el-option
                                                v-for="item in statusProfession"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                        </template>
                                        <!-- 学籍专业  结束 -->
                                        <!-- 专业方向名称  开始 -->
                                        <template v-else-if="row.fieldId == '70'">
                                        <el-select
                                            v-model="row.columnValue"
                                            style="width:100%"
                                            clearable
                                        >
                                            <el-option
                                                v-for="item in ZYFXMCOptions"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                        </template>
                                        <!-- 专业方向名称  结束 -->
                                        <template v-else-if="row.type=='select'">
                                        <el-select
                                            style="width:100%"
                                            :disabled="!row.isUpdate"
                                            v-model="row.columnValue"
                                        >
                                            <el-option
                                                v-for="item in options[row.value]"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                        </template>
                                        <el-date-picker
                                            v-if="row.type=='date'"
                                            v-model="row.columnValue"
                                            type="date"
                                            :disabled="!row.isUpdate"
                                            placeholder="选择日期"
                                            style="width:100%"
                                        ></el-date-picker>
                                        <el-input
                                            v-if="row.type=='textarea'"
                                            type="textarea"
                                            style="width:100%"
                                            autosize
                                            :disabled="!row.isUpdate"
                                            v-model="row.columnValue"
                                            :maxlength="row.length"
                                        ></el-input>
                                        <!-- 入学年级 当前年级 -->
                                        <el-date-picker
                                            v-if="row.type=='year'"
                                            v-model="row.columnValue"
                                            type="date"
                                            placeholder="选择日期"
                                            style="width:100%"
                                        ></el-date-picker>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>    
                    </el-tab-pane>
                </el-tabs>
            </div>
            <div slot="buttons">
                <el-button @click="reset">{{$t("message.reset")}}</el-button>
                <el-button @click="lastStep" v-if="dynamicValidateForms && dynamicValidateForms.length > 0 && activeName != dynamicValidateForms[0].id">上一步</el-button>
                <el-button @click="nextStep" v-if="activeName != lastId">下一步</el-button>
                <el-button @click="save" v-if="activeName == lastId" type="primary">提交激活</el-button>
                <el-button @click="skip" v-if="ifSkip" type="primary">跳过</el-button>
            </div>
        </edu-dialog>
    </div>
</template>
<script>
import { checkActivation, activation, getStationInfoList, findStatusProfessionList, statusInfo, getSetMajorDirectionNames } from "common/src/api/studentinfo";
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import { universities, getCollegeListByNationCode } from "common/src/api/teacherinfo";
import selectForPage from 'common/src/components/common/selectForPage'
export default {
    name: "activation",
    components: {
        'select-For-Page': selectForPage
    },
    data() {
        return {
            closeOnPressEscape: false,
            showClose: false,
            activeName: "",
            lastId: "",
            uid: null,
            options: {},
            endStation: [],
            universList: [],
            statusProfession: [],
            ZYFXMCOptions: [],
            projId: "",
            ifSkip: 0,
            initData: [],
            majorList: [],
            userInfo: {},
            dynamicValidateForms: {
                columns: []
            },
            tabMsg:[
                { label:'父亲（或监护人）姓名',value:'(涉及全日制研究生家庭切身利益，建议至少填写一个监护人完整信息)'},
                { label:'母亲（或监护人）姓名',value:'(涉及全日制研究生家庭切身利益，建议至少填写一个监护人完整信息)'},
                { label:'电子信箱',value:'(常用电子邮箱)'},
                { label:'法定送达地址',value:'(建议家庭固定地址)'},
                { label:'火车终点站',value:'(用于非上海生源研究生登记火车票优惠卡信息，准确填写终点站名称)'}
            ]
                
            
        };
    },
    mounted() {
        let session = localStorage.getItem("sessiondata");
        session = JSON.parse(session);
        //用户类型 1:老师、2:学生、3:本地
        if (
            session && session.mockUser &&
            session.mockUser.uid &&
            session.mockUser.type == 2
        ) {
            this.uid = session.mockUser.uid;
            this.projId = session.mockUser.projId
        } else if (session && session.user && session.user.uid && session.user.type == 2) {
            this.uid = session.user.uid;
            this.projId = session.user.projId
        }
        if (this.uid) {
            this.getUserInfo(this.uid)
            this.getActivationFields();
        }
    },
    methods: {
        // 优化label提示信息
        setLabel(val){
            return val.nameZH
        },
        getActivationFields() {
            checkActivation(this.uid).then(res => {
                if (
                    res.code == 200 &&
                    res.data != true &&
                    res.data.length > 0
                ) {
                    this.$refs.ActiveDialog.open();
                    this.dynamicValidateForms = _.cloneDeep(res.data)
                    this.activeName = this.dynamicValidateForms[0].id
                    this.lastId = this.dynamicValidateForms[this.dynamicValidateForms.length - 1].id
                    this.initData = _.cloneDeep(res.data)  
                    this.ifSkip = res.data[0].stuActivationFieldConfigs[0].isClose === 1
                    this.queryDic();
                }
            });
        },
        // 下一步
        nextStep() {
            for(let key in this.dynamicValidateForms) {
                if((Number(key) + 1) <= this.dynamicValidateForms.length && this.dynamicValidateForms[key].id == this.activeName) {
                    return this.activeName = this.dynamicValidateForms[Number(key)+1].id
                }
            }
        },
        // 上一步
        lastStep() {
            for(let key in this.dynamicValidateForms) {
                if((Number(key) - 1) >= 0 && this.dynamicValidateForms[key].id == this.activeName) {
                   return this.activeName = this.dynamicValidateForms[Number(key)-1].id
                }
            }
        },
        // 提交激活
        save() {
            let flag = true
            this.$refs.activationForm.forEach(act => {
                act.validate(valid => {
                    if(!valid) {
                        flag = false // 轮询校验每个tab页
                    }
                })
            })
            // this.$refs.activationForm.validate(valid => {
                let stuActivationListNow = []
                let initDataList = []
                let stuActivationList = []
                this.dynamicValidateForms.forEach(item => {
                    stuActivationListNow.push(...item.stuActivationFieldConfigs)
                })
                this.initData.forEach(item => {
                    initDataList.push(...item.stuActivationFieldConfigs)
                })

                stuActivationListNow.forEach(item => {
                    initDataList.forEach(val => {
                        if(item.id === val.id && item.columnValue != val.columnValue) {
                            stuActivationList.push(item)
                        }
                    })
                })
                if (flag) {
                    let param = {
                        studentId: this.uid,
                        configId: this.dynamicValidateForms[0].stuActivationFieldConfigs[0].configId,
                        stuActivationFieldConfigs: stuActivationList
                    };
                    activation(param).then(res => {
                        if (res.code == 200) {
                            this.$refs.ActiveDialog.close();
                            this.$message({
                                message: "信息激活成功",
                                type: "success"
                            });
                        }
                    });
                } else {
                    return false;
                }
            // });
        },
        // 跳过
        skip() {
            this.$refs.ActiveDialog.close();
        },
        // 重置
        reset() {
            this.initData.forEach(item => {
                item.stuActivationFieldConfigs.forEach(val => {
                    if(val.columnName === "SEX_" && val.value === "G_XBIE"){
                        val.columnValue = String(val.columnValue)
                    }
                })
            })
            this.dynamicValidateForms = _.cloneDeep(this.initData)
            if(this.$refs.activationForm[this.activeName-1]){
                this.$refs.activationForm[this.activeName-1].clearValidate();
            }
        },
        getUserInfo(studentId) {
            statusInfo(studentId).then(res => {
                if(res.code === 200 && res.data && res.data.length > 0) {
                    this.userInfo = res.data[0]
                }
            })
        },
        // 获取火车终点站
        async getStation() {
            this.endStation = []
            await getStationInfoList({}).then(res => {
                if (res.code == 200 && res.data.length > 0) {
                    res.data.forEach(station => {
                        this.endStation.push({
                            label: station.provice + '-' + station.station,
                            value: station.id
                        })
                    })
                }
                
            })
        },
        // 获取导师工号
        getValueToLabel(val,id) {
            this.dynamicValidateForms[1].stuActivationFieldConfigs.map((item)=>{
                if(item.fieldId == id){
                    item.columnValue = val
                }
                if(item.fieldId == id){
                    item.columnValue = val
                }
            })
        },
        // 获取学籍专业
        getStatusProfessionList() {
            let parm = {
                grade: this.userInfo.currentGrade,
                statusFacultyList: [],
            }
            if(this.projId == 1) {
                parm.statusFacultyList = [this.userInfo.statusFaculty]
            } else {
                parm.statusFacultyList = [this.userInfo.faculty]
            }
            findStatusProfessionList(parm).then(resT=> {
                if(resT.code === 200) {
                    resT.data.forEach(val=> {
                        this.statusProfession.push(
                            {
                                label: val.professionName + '(' + val.professionCode + ')',
                                value: val.statusProfessionCode
                            }
                        )
                    })
                }
            })
        },
        // 获取培养专业
        getMajorList(grade) {
            this.majorList = [];
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["G_ZY"],
                filter: {
                    prefix: this.userInfo.faculty,
                    specilaCode: "XY2ZY",
                    facultys: [this.userInfo.faculty],
                    grade: grade,
                    degreeType: this.projId == 1 ? [] : [this.userInfo.degreeType],
                    trainingLevel: this.projId == 1 ? [] : [this.userInfo.trainingLevel],
                }
            };
            queryDic(data).then(res => {
                if (res.code === 200)
                    UTILS.fillSelect(
                        {
                            profession: "G_ZY"
                        },
                        res.data,
                        this.options
                    );
                this.majorList = this.options.profession.map((item) => {
                    return {
                        key: item.value,
                        label: item.label + "(" + item.value + ")",
                        value: String(item.value)
                    }
                })
            });
        },
        getUniversities(code) {
            if(this.projId == '1') {
                // 本科生获取合作院校
                universities({code: code}).then(res=> {
                    if(res.code === 200) {
                        res.data.forEach(val=> {
                            this.universList.push(
                                {
                                    label: val.universityNameZN,
                                    value: val.universityCode
                                }
                            )
                        })
                    }
                })
            } else if(this.projId == '2') {
                // 研究生获取合作院校
                getCollegeListByNationCode({code: code, collegeId: ''}).then(res=> {
                    if(res.code === 200) {
                        res.data.forEach(val=> {
                            this.universList.push(
                                {
                                    label: val.collegeName,
                                    value: val.collegeCode
                                }
                            )
                        })
                    }
                })
            }
        },
        async getProfessDirectNames(val) {
            let _this = this
            _this.ZYFXMCOptions = []
                // const directionNameRes = await getMajorDirectionNames(val)
                getSetMajorDirectionNames({
                    grade: this.userInfo.currentGrade,
                    pageNum_: 1,
                    pageSize_: 999999,
                    professionCode: val
                }).then(directionNameRes => {
                    if (directionNameRes.code === 200 && Array.isArray(directionNameRes.data.list) && directionNameRes.data.list.length > 0) {
                        _this.ZYFXMCOptions = directionNameRes.data.list.map(value => {
                            return {
                                label: this.$store.getters.language === 'en' ? value.nameEn : value.name,
                                value: value.code
                            }
                        })
                    }
                })
        },
        queryDic() {
            let keys = [];
            this.dynamicValidateForms.forEach(val => {
                val.stuActivationFieldConfigs.forEach(item => {
                    if(item.type === 'year'){
                        item.columnValue = String(item.columnValue)
                    }
                    if(item.columnName === "SEX_" && item.value === "G_XBIE") {
                        if(item.columnValue != null){
                            item.columnValue = String(item.columnValue) // 后端返回的性别value值存在 数据类型不一致情况，统一转成String类型
                        }else{
                            item.columnValue = null
                        }
                        keys.push(item.value);
                    } else if(item.fieldId == "166") {
                        this.getUniversities("") // 合作院校需要单独获取
                    } else if(item.fieldId == "68") {
                        this.getStatusProfessionList() // 学籍专业需要单独获取
                    } else if(item.fieldId == "69") {
                        this.getMajorList(this.userInfo.currentGrade) // 培养专业需要单独获取
                    } else if(item.fieldId == "70") {
                        this.getProfessDirectNames("") // 专业方向名称
                    } else if (
                        item.type == "select" &&
                        item.value &&
                        !keys.includes(item.value)
                    ) {
                        keys.push(item.value);
                    } 

                })
            });
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: keys
            };
            queryDic(data).then(res => {
                if (res.code === 200) {
                    let _that = this;
                    let _fill = function(type, data) {
                        for (const key in data[type]) {
                            _that.options[type].push({
                                value: key,
                                label: data[type][key]
                            });
                        }
                    };
                    keys.forEach(key => {
                        // 火车终点站需要特殊处理，从接口获取数据
                        if(key === "end_station") {
                            this.getStation()
                        } else {
                            this.$set(this.options, key, []);
                            _fill(key, res.data);

                        }
                        
                    });
                }
            });
        },
        getRules(column) {
            let rules = [];
            let trig = "blur"
            if (column.isRequired) {
                let actionType = "必须填写";
                if (column.type == "select") {
                    actionType = "必须选择";
                    trig = "change"
                }
                rules.push({
                    required: true,
                    message: actionType + column.nameZH,
                    trigger: trig
                });
            }
            return rules;
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
#IE-target-form .el-col-12{
    height: 84px;
}
.setSize{
    color: #ff0000be;
    font-size: 12px;
}
.titleMsg{
    color: #ff0000d5;
    font-size: 12px;
}
::v-deep .el-tabs{
    margin-top: 10px;
}
::v-deep.edu-dialog_wrapper .el-dialog .edu-dialog_body{
    padding-top: 20px;
}
</style>
